import router from '@/router/index'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from './utils/get-page-title'

const whiteList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const token = store.state.user.token
  document.title = getPageTitle(to.meta.title)
  if (token) {
    if (to.path === '/login') {
      console.log('有token 自己跳转首页')
      next('/')
      NProgress.done()
      // next('')指定了跳转的地址 就不会经过 router.afterEach函数
      // next()  只有放行的时候才会触发 router.afterEach函数
    } else {
      if(!store.state.user.userInfo.userId){
        await store.dispatch('user/getUserInfoProfile')
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      console.log('没有token  去登录')
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  NProgress.done()
})
